package util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import dao.User_Dao;
import dao.impl.User_DaoImpl;
import domain.Node;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/QRCodeUtil")
public class QRCodeUtil extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置页面编码
        response.setContentType("image/png");
        request.setCharacterEncoding("utf-8");
        //获取传过来的IMEI号
        String IMEI = request.getParameter("IMEI");
        System.out.println("二维码的IMEI："+IMEI);
        /*设置返回的类型，告诉浏览器这是个附件*/
        response.setHeader("Content-Disposition","attachment; filename="+IMEI+".png");

        /*设置基础属性*/
        int width=400;
        int hight=400;
        String format="png";
        String content="http://81.68.160.188:8080/Graduation_project/?IMEI="+IMEI;
        String pressText = "IMEI: "+IMEI;

        //设置额外参数
        Map map = new HashMap();
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        map.put(EncodeHintType.MARGIN,2);
        map.put(EncodeHintType.CHARACTER_SET,"utf-8");

        try {
            BitMatrix encode =  new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,width,hight,map);

            MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
            /*调用添加文字logo的方法*/
            BufferedImage bufferedImage = LogoMatrix(MatrixToImageWriter.toBufferedImage(encode,matrixToImageConfig), new File("C:\\IDEA\\Graduation_project\\web\\images\\logo.jpg"),pressText);
            /*输出图片*/
            ImageIO.write(bufferedImage, format, response.getOutputStream());//输出带logo图片
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    /**
     * 二维码添加logo
     * @param matrixImage 源二维码图片
     * @param logoFile logo图片
     * @param pressText 添加的文字
     * @return 返回带有logo的二维码图片
     */
    public static BufferedImage LogoMatrix(BufferedImage matrixImage, File logoFile,String pressText ) throws IOException {
        /**
         * 读取二维码图片，并构建绘图对象
         */
        Graphics2D g2 = matrixImage.createGraphics();

        int matrixWidth = matrixImage.getWidth();
        int matrixHeigh = matrixImage.getHeight();

        /**
         * 读取Logo图片
         */
        BufferedImage logo = ImageIO.read(logoFile);

        //开始绘制图片
        g2.drawImage(logo,matrixWidth/5*2,matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5, null);//绘制
        BasicStroke stroke = new BasicStroke(5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
        g2.setStroke(stroke);// 设置笔画对象
        //指定弧度的圆角矩形
        RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth/5*2, matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5,20,20);
        g2.setColor(Color.white);
        g2.draw(round);// 绘制圆弧矩形

        //设置logo 有一道灰色边框
        BasicStroke stroke2 = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
        g2.setStroke(stroke2);// 设置笔画对象
        RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth/5*2+2, matrixHeigh/5*2+2, matrixWidth/5-4, matrixHeigh/5-4,20,20);
        g2.setColor(new Color(128,128,128));
        g2.draw(round2);// 绘制圆弧矩形

        //添加下面的文字
        pressText = new String(pressText.getBytes(), "utf-8");
        g2.setColor(Color.BLACK);
        Font font = new Font("宋体", Font.PLAIN, 24);
        FontMetrics metrics = g2.getFontMetrics(font);

        // 文字在图片中的坐标 这里设置在中间
        int startX = (400 - metrics.stringWidth(pressText)) / 2;
        int startY = 440 - 40;
        g2.setFont(font);
        g2.drawString(pressText, startX, startY);

        g2.dispose();
        matrixImage.flush() ;
        return matrixImage ;
    }

    /**
     * 给二维码图片加上文字
     */
    public static void pressText(String pressText, BufferedImage image) throws IOException {
        pressText = new String(pressText.getBytes(), "utf-8");
        Graphics g = image.createGraphics();
        g.setColor(Color.BLACK);
        Font font = new Font("宋体", Font.PLAIN, 24);
        FontMetrics metrics = g.getFontMetrics(font);

        // 文字在图片中的坐标 这里设置在中间
        int startX = (400 - metrics.stringWidth(pressText)) / 2;
        int startY = 440 - 40;
        g.setFont(font);
        g.drawString(pressText, startX, startY);
        g.dispose();
    }
}
